package com.xxl.job.executor.repository;

import com.xxl.job.executor.common.RedisKeyConstant;
import com.xxl.job.executor.model.GatherMjModel;
import com.xxl.job.executor.utils.JSONUtils;
import com.xxl.job.executor.utils.MapUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: xxl-job
 * @description: 门禁
 * @author: XianJin.Lu
 * @create: 2021-09-07 10:43
 **/
@Repository
public class GatherMjRepository {

    private static final Logger LOGGER = LoggerFactory.getLogger(GatherDefRepository.class);

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 获取门禁配置信息 多个
     * @param gatherId
     * @return
     */
    public List<GatherMjModel> findGatherMjModelList(String gatherId){

        List<GatherMjModel> gatherMjModellList = new ArrayList<>();

        //通过  gatherId  获取redis中  习友路门禁信息
        BoundHashOperations<String, String, String> valueOperations = redisTemplate.boundHashOps(RedisKeyConstant.KEY_HASH_POW_DEF_GATHER);

        List<String>    JsonList = MapUtil.getLikeByMap(valueOperations.entries(),gatherId+"_");
        if (JsonList != null && JsonList.size() > 0){

            for (String gatherDefModelStr : JsonList) {

                if (StringUtils.isNotBlank(gatherDefModelStr)) {
                    try {
                        GatherMjModel gdm = JSONUtils.json2pojo(gatherDefModelStr, GatherMjModel.class);
                        //找到 gatherId相同的实体 存放在  gatherMjModellList 中
                        if(gatherId.equals(gdm.getGatherId())){
                            gatherMjModellList.add(gdm);
                        }
                    } catch (IOException e) {
                        LOGGER.error("获取门禁配置信息终端JSON='{}' 转换异常！", gatherDefModelStr, e);
                    }
                }
            }
            return gatherMjModellList;
        }else {
            LOGGER.warn("没有 gatherid='{}' 对应的信号配置缓存！", gatherId);
            return null;
        }
    }
}
